package com.adtech.farmProducts.activities.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.adtech.common.Common;
import com.adtech.common.http.AsyncHttpPostFormData;
import com.adtech.common.http.AsyncHttpResponse;
import com.adtech.common.http.AsyncOkHttpClient;
import com.adtech.common.http.AsyncResponseHandler;
import com.adtech.common.model.RspModel;
import com.adtech.common.utils.AccountManagers;
import com.adtech.common.utils.FileUtils;
import com.adtech.farmProducts.App;
import com.adtech.farmProducts.R;
import com.adtech.farmProducts.base.BaseActivity;
import com.adtech.farmProducts.base.BaseNfcActivity;
import com.adtech.farmProducts.model.CommodityTypeItem;
import com.adtech.farmProducts.model.FUserInfo;
import com.adtech.farmProducts.utils.Constants;
import com.adtech.farmProducts.widget.ClearTextIconEditText;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yalantis.ucrop.UCrop;

import java.io.IOException;
import java.lang.reflect.Type;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

/**
 * Time:2020/6/20
 * Created by xiaocz
 * Describe 新增商品
 */
public class AddCommodityActivity extends BaseNfcActivity {

    @BindView(R.id.edit_name)
    ClearTextIconEditText edit_name;
    @BindView(R.id.tv_type)
    TextView tv_type;
    @BindView(R.id.edit_address)
    ClearTextIconEditText edit_address;
    @BindView(R.id.edit_gs_name)
    TextView edit_gs_name;
    @BindView(R.id.layout_camera)
    LinearLayout layout_camera;

    /**
     * DATA
     */
    private CommodityTypeItem typeItem;

    public static void show(Context context) {
        Intent intent = new Intent(context, AddCommodityActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutSourceId() {
        return R.layout.activity_add_commodity;
    }

    @OnClick({R.id.tv_type, R.id.btn_location, R.id.layout_camera, R.id.btn_submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_type:
                Intent intent = new Intent(mContext, CommodityTypeActivity.class);
                startActivityForResult(intent, 200);
                break;
            case R.id.btn_location:
                hideKeyboard();
                if (Constants.getLocation() != null) {
                    String address = Constants.getLocation().getAddress();
                    if (address != null) {
                        int index = address.indexOf("靠近");
                        edit_address.setText(index > 0 ? address.substring(0, index) : address);
                    }
                }
                break;
            case R.id.layout_camera:
                checkAndRequestPermission();
                break;
            case R.id.btn_submit:
                onCheck();
                break;
        }
    }

    @OnCheckedChanged({R.id.ck_gs_name})
    public void OnCheckedChangeListener(CompoundButton view, boolean isCheck) {
        switch (view.getId()) {
            case R.id.ck_gs_name:
                hideKeyboard();
                if (isCheck) {
                    FUserInfo info = new Gson().fromJson(AccountManagers.getAccount(), FUserInfo.class);
                    edit_gs_name.setText(info.getInfo().getCompanyName());
                } else {
                    edit_gs_name.setText("");
                }
                break;
        }
    }

    /**
     * 数据效验
     */
    private void onCheck() {
        String valueName = String.valueOf(edit_name.getText()).trim();
        String valueType = String.valueOf(tv_type.getText()).trim();
        String valueAddress = String.valueOf(edit_address.getText()).trim();
        String valueGsName = String.valueOf(edit_gs_name.getText()).trim();
        if (TextUtils.isEmpty(valueName)) {
            App.getInstance().showMessage("请输入产品名称！");
            return;
        }
        if (TextUtils.isEmpty(valueType) || typeItem == null) {
            App.getInstance().showMessage("请选择产品类别！");
            return;
        }
        if (TextUtils.isEmpty(valueAddress)) {
            App.getInstance().showMessage("请输入地址！");
            return;
        }
        if (TextUtils.isEmpty(valueGsName)) {
            App.getInstance().showMessage("请输入生产企业名称！");
            return;
        }
        addCommodity(valueAddress, valueName, typeItem.getProductTypeId(), valueGsName);
    }

    /**
     * 数据录入
     */
    private void addCommodity(String address, String productName, int productTypeId, String production) {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("companyId", new Gson().fromJson(AccountManagers.getAccount(), FUserInfo.class).getInfo().getCompanyId());
        asyncHttpPostFormData.addFormData("address", address);//必填：地址
        asyncHttpPostFormData.addFormData("productName", productName);//必填：产品名称
        asyncHttpPostFormData.addFormData("productTypeId", productTypeId);//必填：产品类别ID
        asyncHttpPostFormData.addFormData("production", production);//必填：生产企业名称
        asyncHttpPostFormData.addFormData("qualificationUrl", imageUrl);//图片地址（多张图片用英文逗号隔开）
        asyncHttpPostFormData.addFormData("userId", AccountManagers.getUserId());//必填：会员ID
        okHttpClient.posts(Common.Constant.API_IP + "product/add", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                App.getInstance().showMessage(getResources().getString(R.string.connection_error));
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<String>>() {
                }.getType();
                RspModel<String> rspModel = getAnalysis(response, type, "用户登录");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 1:
                        imageUrl = "";
                        App.getInstance().showMessage("新增成功！");
                        setResult(200);
                        finish();
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 如果裁剪错误则直接返回不做任何操作
        if (resultCode == UCrop.RESULT_ERROR) {
            return;
        }
        // 如果有返回值
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CAMERA_REQUEST_CODE: // 拍照
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        cropRawPhoto(providerUri);
                    } else {
                        cropRawPhoto(mUri);
                    }
                    break;
                case GALLERY_REQUEST_CODE:// 相册选择
                    cropRawPhoto(data.getData());
                    break;
                case CROP_REQUEST_CODE:
                    Uri uri = UCrop.getOutput(data);
                    if (uri != null) {
                        upHeardImage(FileUtils.getFilePathByUri(mContext, uri), layout_camera);
                    } else {
                        App.getInstance().showMessage("获取内容为空！");
                    }
                    break;
                default:
                    break;
            }
        } else if (requestCode == 200 && resultCode == 200) {
            typeItem = (CommodityTypeItem) data.getSerializableExtra("CommodityTypeItem");
            tv_type.setText(typeItem.getProductTypeName());
        }
    }
}
